package com.cloudcc.mobile.view.dynamic;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.OnClick;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.cloudcc.cloudframe.bus.BaseEvent;
import com.cloudcc.cloudframe.bus.DynamicEventList.SendDynamicEvent;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.net.IServer;
import com.cloudcc.cloudframe.util.PackageUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.AddmicroPostGridviewAdapter;
import com.cloudcc.mobile.adapter.AddmicroPostGridviewAdapter.OnAddImageListener;
import com.cloudcc.mobile.adapter.AddmicroPostGridviewAdapter.OnShowImageListener;
import com.cloudcc.mobile.adapter.AddmicroPostGridviewAdapter.OndeleteListener;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostDMany;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostF;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostL;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostV;
import com.cloudcc.mobile.entity.addmicropost.Option;
import com.cloudcc.mobile.event.refresh.RefreshDynamicListEvent;
import com.cloudcc.mobile.manager.LocationManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.DynamicControl;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.activity.AtContaxtActivity;
import com.cloudcc.mobile.view.activity.BindActivity;
import com.cloudcc.mobile.view.activity.GroupActivity;
import com.cloudcc.mobile.view.activity.SelectPhotoActivity;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.wel.WelcomeActivity;
import com.cloudcc.mobile.weight.GridViewForListView;

/**
 * 发布微帖
 * 
 * @author seven
 * 
 */
public class SendTimeLineActivity extends BaseActivity implements
		OnClickListener, IEventLife {
	public static final String KEY_PHOTO_PATH = "photo_path";
	private static final int SELECT_PHOTO = 5000;
	private static final int TAKE_PHOTO = 5001;
	private static final int ADDMICROPOST_ACTIVITY_AT = 7001;
	private static final int INTENT_QX = 7007;

	@Bind(R.id.title)
	TextView tvUserName;
	@Bind(R.id.tv1)
	TextView tvAddress;
	@Bind(R.id.dynamic_content)
	EditText etDynamicContent;
	@Bind(R.id.quanxian)
	TextView quanxian;
	@Bind(R.id.dingwei)
	RelativeLayout dingwei;
	/**
	 * 图片 列表 容器
	 */
	@Bind(R.id.gridview1)
	GridViewForListView containerGridViewPhoto;
	/**
	 * 连接的容器
	 */
	@Bind(R.id.newlinked)
	TableLayout containerLink;

	/**
	 * 连接 中 连接的url
	 */
	@Bind(R.id.linkedurl)
	EditText etLinkUrl;

	/**
	 * 连接 中 网址详情
	 */
	@Bind(R.id.ms)
	EditText etLinkUrlDesc;
	/**
	 * 投票的容器
	 */
	@Bind(R.id.toupiao)
	LinearLayout containerVote;

	/**
	 * 投票 添加 选项
	 */
	@Bind(R.id.addView)
	Button voteAddOps;

	/**
	 * 投票的选项布局 容器
	 */
	@Bind(R.id.buju)
	LinearLayout voteOptionLayout;

	private DynamicType mDynamicType = DynamicType.COMMON;
	/**
	 * 当前的 图片数量
	 */
	private List<AddImageInfo> imageArray = new ArrayList<AddImageInfo>();

	private boolean dwflag = false;

	@Bind(R.id.kongbai)
	TextView kongbai;

	@Bind(R.id.oneedittext1)
	EditText oneedittext1;
	@Bind(R.id.oneedittext2)
	EditText oneedittext2;

	@Bind(R.id.huoqu)
	Button huoqu;

	private ArrayList<View> editViews = new ArrayList<View>();// 动态的布局
	private AddmicroPostGridviewAdapter adapter;

	private String imagename;
	private Uri photoUri;
	public static String picPath = null;

	private String group_name, group_id;
	private String relevantId = "";

	private DynamicControl dynamicControl = new DynamicControl();

	@Override
	public void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		// 检测是不是正在运行状态
		boolean running = PackageUtils.isRunning(mContext,
				mContext.getPackageName());
		if (!running) {
			AppContext.isFenXiang = true;
			Intent intent = new Intent(mContext, WelcomeActivity.class);
			startActivity(intent);
			this.finish();
		}
		register();
		setupView();
		initLocation();
	}

	private void setupView() {
		relevantId = getIntent().getStringExtra("relevantId");
		tvUserName.setText(UserManager.getManager().getUser().userName);
		tvAddress.setText("正在定位......");
		adapter = new AddmicroPostGridviewAdapter(this, imageArray);
		containerGridViewPhoto.setAdapter(adapter);
		setAdapterListener();
	}

	private void initLocation() {
		LocationManager.getInstance().registerListener(mListener);
		LocationManager.getInstance().requestLocal();
	}

	private void refreshType() {

		if (containerGridViewPhoto.getVisibility() == View.VISIBLE
				&& imageArray.size() > 0) {// 图片
			mDynamicType = DynamicType.PHOTO;
			return;
		}
		if (containerVote.getVisibility() == View.VISIBLE) {
			mDynamicType = DynamicType.VOTE;
			return;
		}
		if (containerLink.getVisibility() == View.VISIBLE) {
			mDynamicType = DynamicType.LINK;
			return;
		}
		mDynamicType = DynamicType.COMMON;

	}

	/**
	 * 发布 投票 动态
	 */
	private void sendVoteDynamic() {

		AddMicroPostV addMicroPostV = new AddMicroPostV();
		if (!dwflag && null != lastDBLocation) {
			addMicroPostV.setLatitude(lastDBLocation.getLatitude());
			addMicroPostV.setLongitude(lastDBLocation.getLongitude());
			addMicroPostV.setAddress(LocationManager.getDetailAddr(
					lastDBLocation, false));
		}
		if (relevantId != null) {
			addMicroPostV.setTargetType("record");
			addMicroPostV.setTargetId(relevantId);
		}
		if (group_id != null && !group_id.equals("")) {
			addMicroPostV.setTargetType("group");
			addMicroPostV.setTargetId(group_id);
		}
		ArrayList<Option> options = new ArrayList<Option>();

		String op1 = oneedittext1.getText().toString().trim();
		String op2 = oneedittext2.getText().toString().trim();
		String voteTitle = etDynamicContent.getText().toString().trim();// 投票主题

		if (StringUtils.isBlank(voteTitle)) {
			Tools.showInfo(this, "请填写投票主题");
			return;
		}
		if (StringUtils.isBlank(op1) || StringUtils.isBlank(op2)) {
			Tools.showInfo(this, "请至少填写2个选项");
			return;
		}
		Option option1 = new Option();
		option1.setOption(op1);
		Option option2 = new Option();
		option2.setOption(op2);
		options.add(option1);
		options.add(option2);

		if (editViews.size() > 0) {
			for (int i = 0; i < editViews.size(); i++) {
				EditText text1 = (EditText) editViews.get(i).findViewById(
						R.id.xged);
				String xx = text1.getText().toString().trim();
				if (!Tools.isNull(xx)) {
					Option oo = new Option();
					oo.setOption(text1.getText().toString().trim());
					options.add(oo);
				}
			}
		}
		addMicroPostV.setBody(voteTitle);
		String aaaa = Json.toJson(options);
		addMicroPostV.setPollOptions(aaaa);
		onSend(addMicroPostV, IServer.SERVICENAME_VOTE);

	}

	/**
	 * 发布连接动态
	 */
	private void sendLinkDynamic() {
		AddMicroPostL addMicroPostL = new AddMicroPostL();
		if (!dwflag && null != lastDBLocation) {
			addMicroPostL.setLatitude(lastDBLocation.getLatitude());
			addMicroPostL.setLongitude(lastDBLocation.getLongitude());
			addMicroPostL.setAddress(LocationManager.getDetailAddr(
					lastDBLocation, false));
		}
		if (relevantId != null) {
			addMicroPostL.setTargetType("record");
			addMicroPostL.setTargetId(relevantId);
		}
		if (group_id != null && !group_id.equals("")) {
			addMicroPostL.setTargetType("group");
			addMicroPostL.setTargetId(group_id);
		}
		addMicroPostL.setBody(etDynamicContent.getText().toString().trim());
		String name = etLinkUrlDesc.getText().toString().trim();
		String url = etLinkUrl.getText().toString().trim();

		if (StringUtils.isBlank(url)) {
			Tools.showInfo(this, "请输入网址");
			return;
		}
		if (url.length() < 8) {
			Tools.showInfo(mContext, "网址写法不合格");
			return;
		}
		String h = url.substring(0, 7);
		if (!h.equals("http://")) {
			addMicroPostL.setLinkValue("http://" + url);
		} else {
			addMicroPostL.setLinkValue(url);
		}
		addMicroPostL.setLinkName(name);
		onSend(addMicroPostL, IServer.SERVICENAME_LINK);

	}

	/**
	 * 发送图片
	 */
	private void sendPhotoDynamic() {
		AddMicroPostDMany addMicroPostDMany = new AddMicroPostDMany();
		if (!dwflag && null != lastDBLocation) {
			addMicroPostDMany.setLatitude(lastDBLocation.getLatitude());
			addMicroPostDMany.setLongitude(lastDBLocation.getLongitude());
			addMicroPostDMany.setAddress(LocationManager.getDetailAddr(
					lastDBLocation, false));
		}
		if (relevantId != null) {
			addMicroPostDMany.setTargetType("record");
			addMicroPostDMany.setTargetId(relevantId);
		}
		if (group_id != null && !group_id.equals("")) {
			addMicroPostDMany.setTargetType("group");
			addMicroPostDMany.setTargetId(group_id);
		}
		addMicroPostDMany.setBody(etDynamicContent.getText().toString().trim());
		showWainting("正在上传图片...");
		dynamicControl.sendPhotoDynamic(imageArray, addMicroPostDMany);

	}

	/**
	 * 发送普通的动态
	 */
	private void sendCommonDynamic() {
		AddMicroPostF addMicroPostF = new AddMicroPostF();
		if (!dwflag && null != lastDBLocation) {
			addMicroPostF.setLatitude(lastDBLocation.getLatitude());
			addMicroPostF.setLongitude(lastDBLocation.getLongitude());
			addMicroPostF.setAddress(LocationManager.getDetailAddr(
					lastDBLocation, false));
		}
		if (relevantId != null) {
			addMicroPostF.setTargetType("record");
			addMicroPostF.setTargetId(relevantId);
		}
		if (group_id != null && !group_id.equals("")) {
			addMicroPostF.setTargetType("group");
			addMicroPostF.setTargetId(group_id);
		}
		String body = etDynamicContent.getText().toString().trim();

		if (StringUtils.isBlank(body)) {
			Tools.showInfo(mContext, "请输入帖子内容");
			return;
		}
		addMicroPostF.setBody(body);

		onSend(addMicroPostF, IServer.SERVICENAME_FOLLEW);

	}

	@OnClick(R.id.send)
	public void clickSend() {
		refreshType();
		if (mDynamicType == DynamicType.COMMON) {
			sendCommonDynamic();
			return;
		}
		if (mDynamicType == DynamicType.PHOTO) {
			sendPhotoDynamic();
			return;
		}
		if (mDynamicType == DynamicType.LINK) {
			sendLinkDynamic();
			return;
		}
		if (mDynamicType == DynamicType.VOTE) {
			sendVoteDynamic();
			return;
		}
	}

	private void onSend(Object obj, String ServiceName) {
		showWainting("正在发布微贴...");
		dynamicControl.sendCommonDynamic(obj, ServiceName);
	}

	// GridView监听
	private void setAdapterListener() {
		containerGridViewPhoto.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				adapter.setDeleteModel(false);
				return true;
			}
		});
		adapter.setOnAddImageListener(new OnAddImageListener() {
			@Override
			public void add() {
				AppContext.isSelectedNum = imageArray.size();
				Intent intent = new Intent(mContext, SelectPhotoActivity.class);
				startActivityForResult(intent, SELECT_PHOTO);
			}
		});
		adapter.setOndeleteListener(new OndeleteListener() {
			@Override
			public void delete(int posion) {
				imageArray.remove(posion);
				if (imageArray.size() == 0) {
					adapter.setDeleteModel(false);
				} else {
					adapter.notifyDataSetChanged();
				}
			}
		});
		adapter.setOnShowImageListener(new OnShowImageListener() {
			@Override
			public void show(int posion) {
				File file = new File(imageArray.get(posion).getImagePath());
				Intent it = new Intent(Intent.ACTION_VIEW);
				Uri mUri = Uri.parse("file://" + file.getPath());
				it.setDataAndType(mUri, "image/*");
				startActivity(it);
			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_del:
			View view = (View) v.getTag();
			removeView(view);
			break;
		}
	}

	@OnClick(R.id.huoqu)
	public void clickHuoQu() {
		for (int i = 0; i < editViews.size(); i++) {
			EditText text1 = (EditText) editViews.get(i)
					.findViewById(R.id.xged);
			System.out.println(text1.getText());
		}
	}

	/**
	 * 点击投票的时候 的 添加选项
	 */
	@OnClick(R.id.addView)
	public void clickVoteAddOps() {
		if (mDynamicType != DynamicType.VOTE) {
			refreshLayout();
			return;
		}
		if (editViews.size() < 8) {
			View view = LayoutInflater.from(getBaseContext()).inflate(
					R.layout.toupiao_item, null);
			Button btnDel = (Button) view.findViewById(R.id.bt_del);// 删除
			EditText text = (EditText) view.findViewById(R.id.xged);// 输入框
			btnDel.setTag(view);
			btnDel.setOnClickListener(this);
			LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
			voteOptionLayout.addView(view, params);
			editViews.add(view);
		} else {
			Tools.showInfo(mContext, "亲~ 最多可有10个投票选项");
		}
	}

	/**
	 * 选择 帖子的类型
	 */
	@OnClick(R.id.quanxian)
	public void clickLimit() {
		Intent ia = new Intent(SendTimeLineActivity.this, GroupActivity.class);
		ia.putExtra("quanxian", quanxian.getText().toString());
		startActivityForResult(ia, INTENT_QX);
	}

	@OnClick(R.id.tv1)
	public void clickLocation() {
		if (dwflag) {
			tvAddress.setText(null==lastDBLocation?"正在定位...":LocationManager.getDetailAddr(lastDBLocation, false));
			dwflag = false;
		} else {
			tvAddress.setText("插入位置");
			dwflag = true;
		}
	}

	/**
	 * 点击投票
	 */
	@OnClick(R.id.tianjia)
	public void clickVote() {
		mDynamicType = containerVote.getVisibility() == View.VISIBLE ? DynamicType.COMMON
				: DynamicType.VOTE;
		refreshLayout();
	}

	/**
	 * 点击连接
	 */
	@OnClick(R.id.xiaolian)
	public void clickLink() {
		mDynamicType = containerLink.getVisibility() == View.VISIBLE ? DynamicType.COMMON
				: DynamicType.LINK;
		refreshLayout();
	}

	/**
	 * 点击相册
	 */
	@OnClick(R.id.wenjian)
	public void clickGallery() {
		Intent intent = new Intent(mContext, SelectPhotoActivity.class);
		startActivityForResult(intent, SELECT_PHOTO);
	}

	private void refreshLayout() {
		containerLink.setVisibility(View.GONE);
		kongbai.setVisibility(View.GONE);
		containerVote.setVisibility(View.GONE);
		containerGridViewPhoto.setVisibility(View.GONE);
		if (mDynamicType == DynamicType.PHOTO) {
			containerGridViewPhoto.setVisibility(View.VISIBLE);
			dingwei.setVisibility(View.VISIBLE);
			return;
		}
		// 如果不是图片的话 先清空
		imageArray.clear();
		if (mDynamicType == DynamicType.LINK) {
			containerLink.setVisibility(View.VISIBLE);
			dingwei.setVisibility(View.VISIBLE);
			return;
		}
		if (mDynamicType == DynamicType.VOTE) {
			containerVote.setVisibility(View.VISIBLE);
			dingwei.setVisibility(View.VISIBLE);
		}

	}

	/**
	 * 点击相机
	 */
	@OnClick(R.id.paizhao)
	public void clickCamera() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			File dir = new File(Environment.getExternalStorageDirectory() + "/"
					+ "CloudCC/photo/");
			if (!dir.exists())
				dir.mkdirs();
			imagename = Tools.getTimeName(System.currentTimeMillis());
			Intent intent = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			File f = new File(dir, imagename);// localTempImgDir和localTempImageFileName是自己定义的名字
			Uri u = Uri.fromFile(f);
			intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
			startActivityForResult(intent, TAKE_PHOTO);
		} else {
			Tools.showInfo(SendTimeLineActivity.this, "请插入SD卡");
		}
	}

	private void removeView(View view) {
		voteOptionLayout.removeView(view);
		editViews.remove(view);
	}

	@OnClick(R.id.back)
	public void onClickBack() {
		finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode != Activity.RESULT_OK) {
			return;
		}
		if (requestCode == SELECT_PHOTO) {// 选图片
			mDynamicType = DynamicType.PHOTO;
			setPhotos();
		} else if (requestCode == TAKE_PHOTO) {// 照相
			mDynamicType = DynamicType.PHOTO;
			if (imageArray.size() + 1 > 9) {
				Tools.showInfo(mContext, "最多添加9张图片");
			} else {
				File f = new File(Environment.getExternalStorageDirectory()
						+ "/" + "CloudCC" + "/photo/" + imagename);
				try {
					Uri u = Uri.parse(android.provider.MediaStore.Images.Media
							.insertImage(getContentResolver(),
									f.getAbsolutePath(), null, null));
					String imageurl = getAbsoluteImagePath(u);
					AddImageInfo imageInfo = new AddImageInfo();
					imageInfo.setImagePath(imageurl);
					imageArray.add(imageInfo);
					setPhotos();
				} catch (FileNotFoundException e) {
					Tools.handle(e);
				}
			}
		} else if (requestCode == ADDMICROPOST_ACTIVITY_AT) {// @某人
			String a = data.getStringExtra("name");
			String[] c = a.split(",");
			for (int i = 0; i < c.length; i++) {
				if (!c[i].equals("")) {
					etDynamicContent.append(" @[" + c[i] + "]" + " ");
				}
			}
		} else if (requestCode == INTENT_QX) {// 权限返回的数据
			group_name = data.getStringExtra("groupname");
			quanxian.setText(group_name);
			group_id = data.getStringExtra("groupid");
		}
		refreshLayout();
	}

	Handler handler2 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Tools.showInfo(mContext, "最多添加9张图片");
				break;
			case 2:
				adapter = new AddmicroPostGridviewAdapter(
						SendTimeLineActivity.this, imageArray);
				containerGridViewPhoto.setAdapter(adapter);
				containerGridViewPhoto.setVisibility(View.VISIBLE);
				setAdapterListener();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	/**
	 * 设置选中的 图片
	 */
	private void setPhotos() {
		List<String> selectedImagePathArray = AppContext.selectPhotos;
		if (imageArray.size() + selectedImagePathArray.size() > 9) {
			selectedImagePathArray.clear();
			Tools.showInfo(mContext, "最多添加9张图片");
			return;
		}
		for (String imagePath : selectedImagePathArray) {
			if (imageArray.contains(imagePath)) {// 去重
				continue;
			}
			AddImageInfo imageInfo = new AddImageInfo();
			imageInfo.setImagePath(imagePath);
			imageArray.add(imageInfo);
		}
		adapter = new AddmicroPostGridviewAdapter(mContext, imageArray);
		containerGridViewPhoto.setAdapter(adapter);
		setAdapterListener();
		selectedImagePathArray.clear();
	}

	private void shareImage() {
		Bundle data = getIntent().getExtras();
		if (data != null) {
			// if (AppContext.islogining) {
			Uri imgUri = (Uri) data.getParcelable(Intent.EXTRA_STREAM);
			String urlpath = getAbsoluteImagePath(imgUri);
			AddImageInfo imageInfo = new AddImageInfo();
			imageInfo.setImagePath(urlpath);
			if (imageArray.size() != 0) {
				for (int i = 0; i < imageArray.size(); i++) {
					if (urlpath.equals(imageArray.get(i).getImagePath())) {
						AppContext.isFenXiang = false;
					} else {
						AppContext.isFenXiang = true;
					}
				}
			} else {
				AppContext.isFenXiang = true;
			}
			if (AppContext.isFenXiang) {
				imageArray.add(imageInfo);
				adapter.changeData(imageArray);
			}
			containerGridViewPhoto.setVisibility(View.VISIBLE);
			dingwei.setVisibility(View.VISIBLE);
			AppContext.isBundle = null;
			// } else {
			// AppContext.isBundle = data;
			// Intent intent = new Intent(mContext, WelcomeActivity.class);
			// startActivity(intent);
			// AppContext.isFenXiang = true;
			// finish();
			// }
		} else {
			if (AppContext.isBundle != null) {
				Uri imgUri = (Uri) AppContext.isBundle
						.getParcelable(Intent.EXTRA_STREAM);
				String urlpath = getAbsoluteImagePath(imgUri);
				AddImageInfo imageInfo = new AddImageInfo();
				imageInfo.setImagePath(urlpath);
				if (AppContext.isFenXiang) {
					imageArray.add(imageInfo);
					adapter.changeData(imageArray);
				}
				containerGridViewPhoto.setVisibility(View.VISIBLE);
				dingwei.setVisibility(View.VISIBLE);
				AppContext.isBundle = null;
				urlpath = "";
			}
		}
	}

	@OnClick(R.id.tingxingmouren)
	public void clickAiTe() {
		Intent intent = new Intent(SendTimeLineActivity.this,
				AtContaxtActivity.class);
		startActivityForResult(intent, ADDMICROPOST_ACTIVITY_AT);
	}

	public void onEventMainThread(SendDynamicEvent event) {
		dismissWainting();
		if (event.isError()) {
			if (event.getStatusCode() == BaseEvent.SC_LOGIN_INVAILED) {// 登录失效
				Intent intent = new Intent(mContext, BindActivity.class);
				mContext.startActivity(intent);
			} else if (event.getStatusCode() == BaseEvent.NET_NO_NETWORK) {// 没有网络
				Tools.showInfo(mContext, "暂无网络...");
			} else {
				Tools.showInfo(mContext, "发布微贴失败,已经保存到草稿箱");
				// 刷新
				Intent caogao = new Intent(AppContext.CAOGAO_NUM);
				mContext.sendBroadcast(caogao);
				finish();
			}
			return;
		}
		EventEngine.post(new RefreshDynamicListEvent());
		finish();

	}

	@Override
	protected void onStop() {

		try {
			AppContext.isFenXiang = false;
		} catch (Exception e) {
			Tools.handle(e);
		}
		super.onStop();
	}

	@Override
	protected void onResume() {
		try {
			shareImage();
		} catch (Exception e) {
			Tools.handle(e);
		}
		super.onResume();
	}

	public String getAbsoluteImagePath(Uri uri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		@SuppressWarnings("deprecation")
		Cursor cursor = managedQuery(uri, proj, // Which columns to return
				null, // WHERE clause; which rows to return (all rows)
				null, // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	@Override
	protected void onDestroy() {
		unRegister();
		LocationManager.getInstance().unregisterlistener(mListener);
		try {
			AppContext.isSelectedNum = 0;
			AppContext.isFenXiang = true;
		} catch (Exception e) {
			Tools.handle(e);
		}
		super.onDestroy();
	}

	private enum DynamicType {
		COMMON, // 普通
		PHOTO, // 图片
		LINK, // 连接
		VOTE, // 投票
	}

	@Override
	public int getLayoutId() {
		return R.layout.act_sendtimeling;
	}

	@Override
	public void register() {
		EventEngine.register(this);

	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}

	private BDLocation lastDBLocation;
	private BDLocationListener mListener = new BDLocationListener() {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (null != location
					&& location.getLocType() != BDLocation.TypeServerError) {
				lastDBLocation = location;
				LocationManager.getInstance().stopRequestLocal();
				LocationManager.log(lastDBLocation);
				refreshTvAddress();
			} else {
				if (null != location) {
					showToast("定位失败，请重试! 错误码:" + location.getLocType());
				}
			}
		}
	};

	private void refreshTvAddress() {
		if (null!=lastDBLocation) {
			tvAddress.setText(LocationManager.getDetailAddr(lastDBLocation, false));
		} else {
			tvAddress.setText("正在定位.....");
		}
	}

}
